package com.qf.air.controller;

import com.qf.air.config.ElasticsearchConfig;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 10537
 * @version V1.0
 * @Date 2021/11/5 16:59
 */
@RestController
@RequestMapping("/echarts")
@CrossOrigin(allowCredentials = "true")
public class EchartsController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @GetMapping("/list")
    public List<Map> districtNameChats() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("air");
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        ssb.aggregation(AggregationBuilders.terms("districtName").field("districtName").size(10));
        ssb.size(0);
        request.source(ssb);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        Terms terms = response.getAggregations().get("districtName");
        List<Map> list = new ArrayList<>();

        for (Terms.Bucket bucket : terms.getBuckets()) {
            Map map = new HashMap();
            map.put("name", bucket.getKey());
            map.put("value", bucket.getDocCount());
            list.add(map);
        }

        return list;
    }
}
